<?php

namespace App\V3\V3_2_6\Controllers;

use App\Services\CommonService;
use App\V3\V3_2_6\Models\SerialNumberModel;
use App\V3\V3_2_6\Services\StorageManageService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\V3\V3_2_6\Models\AdminModel;
use App\V3\V3_2_6\Services\SmsService;
use Illuminate\Support\Facades\Redis;

class StorageManageController extends BaseController
{
    /**
     * 库存列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/3/19 15:06
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
        ], [
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }


        if($this->getUserId() == $this->getMainUserId()) {
            $mainId['storage_manage.main_id'] = ['EQ' => $this->getMainUserId()];
        }
        else {
            if($this->isShareStorage()) {
                $mainId['storage_manage.main_id'] = ['EQ' => $this->getMainUserId()];
            }
            else {
                $mainId['e.user_id'] = ['EQ' => $this->getUserId()];
            }
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['user_type'] = $this->getUserTpye();
        $data['is_share_storage_operate'] = $this->isShareStorageOperate();
        $data['order_type'] = empty($data['order_type'])?0:$data['order_type'];

        if(!in_array($data['order_type'], [0,1,2])) {
            return $this->fail('', '不支持的排序类型');
        }

        $data['order_by'] = empty($data['order_by']) ?'asc':$data['order_by'];

        if(!in_array($data['order_by'], ['desc','asc'])) {
            return $this->fail('', '不支持的排序方式');
        }

        return $this->success(StorageManageService::list($mainId, $data));

    }

    /**
     * 批次列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/7 16:20
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//页面大小
        ], [
            'id.required' => '参数`库存主键id`缺失',
            'id.integer' => '参数`库存主键id`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $result = StorageManageService::batchList($request->id);

        return response()->json(['code' => 0, 'msg' => 'success', 'data' => $result]);
    }

    /**
     * 批次采购详细
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/7 16:23
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchMaterielInfo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//页面大小
        ], [
            'id.required' => '参数`批次主键id`缺失',
            'id.integer' => '参数`批次主键id`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $result = StorageManageService::batchMaterielInfo($request->id);
        return $this->success($result);
    }

    public function readBatchNo(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'batch_no' => 'required',//条码信息
        ], [
            'batch_no.required' => '参数`条码信息`缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return response()->json(
            StorageManageService::readBatchNo($data)
        );
    }

    /**
     * 商品库存批次列表
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/6/24 15:55
     * @return \Illuminate\Http\JsonResponse
     */
    public function materielBatchList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'materiel_type_id' => 'required',//页面大小
            'sell_id' => 'required',
            'pageSize' => 'required|integer',//页面大小
            'currentPage' => 'required|integer',//当前页
            'type' => [
                'required',
                Rule::In([0, 1]),
            ],//条码类型0:商品;1:套餐;
        ], [
            'materiel_type_id.required' => '参数`商品id`缺失',
            'sell_id.required' => '参数`销售单id`缺失',
            'pageSize.required' => '参数`pageSize`缺失',
            'pageSize.integer' => '参数`pageSize`仅能为数字',
            'currentPage.required' => '参数`currentPage`缺失',
            'currentPage.integer' => '参数`currentPage`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return $this->success(
            StorageManageService::materielBatchList(
                $request->materiel_type_id,
                $request->sell_id,
                $request->type,
                $data
            )
        );
    }

    public function fastOutStorage(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'batch_no' => 'required',//页面大小
           'code_type' => 'required',
        ], [
            'batch_no.required' => '参数`编号`缺失',
            'code_type.required' => '参数`码的类型`缺失',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['out_way'] = $this->getOutWay();
        $data['batch_title'] = $this->batchTitle();
        $time=time();
        $this->operateLog('商品或套餐快速出库', $data,$time);

        /**
         * form_type:   0   销售单
         *              1   报溢报损
         *              2   退货
         */
        $formType = isset($data['form_type'])?$data['form_type']:0;
        $data['time']=$time;
        return response()->json(
            StorageManageService::fastOutStorage($data, $formType)
        );
    }

    /**
     * 清除批次信息
     * @param Request $request
     * AUTHOR  : Sun Wu
     * DateTime: 2022/7/13 16:33
     * @return \Illuminate\Http\JsonResponse
     */
    public function clear(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//页面大小
        ], [
            'id.required' => '参数`库存主键id`缺失',
            'id.integer' => '参数`库存主键id`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $this->log('清除库存', $data);

        return response()->json(
            StorageManageService::clear($data)
        );
    }

    /**
     * 直接入库（批量）
     */
    public function directInStorageSeveral(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
//            'storage_id' => 'required|numeric',//仓库id
//            'storage_name' => 'required',//仓库名
//            'status' => [
//                'required',
//                Rule::In([0, 1]),
//            ],//是否设置低库存预警数：0-否 1-是
//            'alert_num' => 'numeric|min:0',
            'goods_info' => 'required'
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        $data['is_use_shelf'] = $this->isUseShelf();
        $data['label_id'] = empty($data['label_id'])?'':$data['label_id'];
        $data['label_name'] = empty($data['label_name']) ? '' : $data['label_name'];
        $time = time();
        $data['in_storage_time'] = empty($data['in_storage_time'])?$time:strtotime($data['in_storage_time']);
//        $data['storage_id'] = empty($data['storage_id'])?0:$data['storage_id'];
//        $data['shelf_id'] = empty($data['shelf_id'])?0:$data['shelf_id'];
//        $data['location_id'] = empty($data['location_id'])?0:$data['location_id'];
        $this->operateLog('新建直接入库', $data, $time);
        $result = StorageManageService::directInStorageSeveral($data, $time);

        CommonService::operateResult($data['user_id'], $time, $result);
        return response()->json(
            $result
        );
    }

    /**
     * 直接出库或批量出库
     * Author: Sw
     * Created at 2023/3/8 17:24
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function directOutStorageSeveral(Request $request)
    {
        $data = $request->all();
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['is_use_shelf'] = $this->isUseShelf();
        $data['label_id'] = empty($data['label_id'])?'':$data['label_id'];
        $data['label_name'] = empty($data['label_name']) ? '' : $data['label_name'];
        $time = time();
        $this->operateLog('直接出库', $data, $time);
        $data['out_storage_time'] = empty($data['out_storage_time'])?$time:strtotime($data['out_storage_time']);
        $result =StorageManageService::directOutStorageSeveral($data, $time);

        CommonService::operateResult($data['user_id'], $time, $result);

        return response()->json($result);
    }

    /**
     * 直接出库 批量
     */
    public function directOutStorageSeveral1(Request $request)
    {
        $data = $request->all();

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['out_storage_way'] = $this->getOutWay();
        $data['is_use_shelf']= $this->isUseShelf();
        $this->log('直接出库', $data);
        if(!$data['out_storage_way']){
            $list = StorageManageService::directOutStorageSeveral($data);
        }else{
            $list = StorageManageService::batchDirectOutStorageSeveral($data);
        }
        return response()->json($list);
    }

    /**
     * 批次列表
     */
    public function serialNoList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'storageManageId' => 'required|numeric',//库存id
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $list = SerialNumberModel::select('serial_no')->where([
            'storage_manage_id' => $data['storageManageId'],
            'status' => SerialNumberModel::UNUSEDSTATUS,]);

        if ($data['search_data']) {
            $list->where('serial_no', 'like', '%' . $data['search_data'] . '%');
        }

        $list = $list->paginate($data['pageSize'], ['*'], '', $data['currentPage']);

        return response()->json(
            ['code' => 0, 'msg' => 'success', 'data' => $list]
        );
    }

    /**
     * 一键清除
     * @param Request $request
     * 2022/9/8 11:00
     * Author: Sun Wu
     * @return \Illuminate\Http\JsonResponse
     */
    public function oneKeyClear(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'clear_storage' => [
                Rule::In([0, 1]),
            ],//清理库存
            'clear_materiel' => [
                Rule::In([0, 1]),
            ],//清理商品
            'clear_class' => [
                Rule::In([0, 1]),
            ],//清理分类
            'code'=>'required',
            'mobile'=>'required',
        ], [
            'clear_storage.in' => '参数`清理库存`异常',
            'clear_materiel.in' => '参数`清理商品`异常',
            'clear_class.in' => '参数`clear_class`异常',
             'code.required'=>'`验证码`不能为空',
            'mobile.required'=>'`手机号`不能为空',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();

        $result = self::checkMobile($data);//校验手机号

        if(!$result == '') {
            return response()->json([
                'code' => 1,
                'msg' => $result,
                'data' => ''
            ]);
        }

        $time = time();
        $this->operateLog('一键清除', $data, $time);
        $result = StorageManageService::oneKeyClear($data);
        CommonService::operateResult($data['main_id'], $time, $result);
        return response()->json(
            $result
        );
    }

    /**
     * 返回主账号手机号（一键清除发送验证码）
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2022/09/23 10:06
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMainPhone(Request $request){

        if($this->getUserId() == $this->getMainUserId() || $this->getMainUserId() == 0){

            $adminInfo = AdminModel::select('mobile')->where('id',$this->getUserId())->first();

        }else{

            $adminInfo = AdminModel::select('mobile')->where('id',$this->getMainUserId())->first();
        }
        $this->log('一键清除-返回主账号手机号', $adminInfo);
        return $this->success($adminInfo);
    }

    /**
     * 一键清除发送验证码
     * @param Request $request
     * AUTHOR  : zlf
     * DateTime: 2022/09/23 10:06
     * @return \Illuminate\Http\JsonResponse
     */
    public function getOneClearCode(Request $request){

        $result = self::checkMobile($request->all());//校验手机号

        if($result == '') {
            if(Redis::exists($request->mobile.'_one_clear')) {

                return response()->json([
                    'code' => 1,
                    'msg' => '验证码已发送，请勿重新点击',
                    'data' => ''
                ]);
            }
            return response()->json(SmsService::sendOneClearCode($request->mobile,config('app.one_clear_temp_id')));
        }
        else {
            return response()->json([
                'code' => 1,
                'msg' => $result,
                'data' => ''
            ]);
        }

    }

    //校验手机号
    public function checkMobile($data) {
        $messages = [
            'mobile.required' => '手机号不能为空，请输入手机号',
            'mobile.regex' => '手机号格式错误，请重试',
        ];

        $validator = Validator::make($data, [
            'mobile' => 'required|regex:/^1[3456789][0-9]{9}$/',
        ], $messages);

        return $validator->errors()->first();
    }

    /**
     * 库存直接入库
     * @param Request $request
     * 2022/9/8 17:32
     * Author: Sun Wu
     * @return \Illuminate\Http\JsonResponse
     */
    public function storageManageIn(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//页面大小
            'num' => 'required|numeric|min:0'
        ], [
            'id.required' => '参数`库存主键id`缺失',
            'id.integer' => '参数`库存主键id`仅能为数字',
            'num.required' => '参数`数量`缺失',
            'num.numeric' => '参数`数量`仅能为数字',
            'num.min' => '参数`数量`最小仅能为0',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['time'] = time();
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        $data['label_id'] = empty($data['label_id'])?'':$data['label_id'];

//        $this->log('库存直接入库',var_export($data, true));
        $this->operateLog('库存直接入库', $data, $data['time']);

        $result = StorageManageService::storageManageIn($data);
        CommonService::operateResult($data['user_id'], $data['time'], $result);
        return response()->json(
            $result
        );
    }

    /**
     * @直接入库
     * @created 在 2021/11/30 11:30 创建
     * @param Request $request
     * @author: Sun Wu
     */
    public function directInStorage(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'materiel_name' => 'required',//物料名称
//            'type_name' => 'required',//物料型号
            'storage_id' => 'required|numeric',//仓库id
            'storage_name' => 'required',//仓库名
            'status' => [
                'required',
                Rule::In([0, 1]),
            ],//是否设置低库存预警数：0-否 1-是
//            'in_storage_time' => 'required|date_format:Y-m-d H:i:s',//入库时间
            'num' => 'required|numeric|min:0',//入库数量
            'alert_num' => 'numeric|min:0'
        ]);

        //参数错误响应
        if($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();
        $this->log('新建直接入库', $data);
        return response()->json(
            StorageManageService::directInStorage($data)
        );
    }

    /**
     * @扫码入库
     * @created 在 2023/2/22 13:47 创建
     * @param Request $request
     * @author: zlf
     */
    public function scanCodesInStorage(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'storage_id' => 'required|numeric',//仓库id
            'code_type' => [
                'required',
                Rule::In([0, 1, 2, 3, 4]),
            ],//码类型：0商品基础二维码，1序列号二维码，2批次号二维码，3条形码
             [
                'storage_id.required' => '参数`库存主键id`缺失',
                'storage_id.numeric' => '参数`库存主键id`仅能为数字',
                'code_type.required' => '参数`码类型`缺失',
            ]
        ]);
        //参数错误响应
        if($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $data['time']=time();
        $this->operateLog('扫码入库', $data,$data['time']);
        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['batch_title'] = $this->batchTitle();

        $result = StorageManageService::scanCodesInStorage($data);
        CommonService::operateResult($data['user_id'], $data['time'], $result);
        return response()->json($result);
    }

    /**
     * @直接出库
     * @created 在 2021/12/2 14:58 创建
     * @param Request $request
     * @author: Sun Wu
     */
    public function directOutStorage(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',//库存物料id
            'num' => 'required|numeric|min:0',//出库数量
        ]);

        //参数错误响应
        if($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['time'] = time();
        $data['label_id'] = empty($data['label_id']) ?'':$data['label_id'];
        $data['label_name'] = empty($data['label_name']) ?'':$data['label_name'];

        $this->operateLog('直接出库', $data, $data['time']);

        $result = StorageManageService::directOutStorage($data);

        CommonService::operateResult($data['user_id'], $data['time'], $result);
        return response()->json(
            $result
        );
    }

    /**
     * @设置低库存预警数
     * @created 在 2021/11/30 16:54 创建
     * @param Request $request
     * @author: Sun Wu
     */
    public function setAlertNum(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',//库存物料id
            'alert_num' => 'required|numeric|min:0'
        ]);

        //参数错误响应
        if($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['main_id'] = $this->getMainUserId();
        $time = time();

        $this->operateLog('设置低库存预警数', $data, $time);
        $result = StorageManageService::setAlertNum($data);
        CommonService::operateResult($this->getUserId(), $time, $result);
        return response()->json(
            $result
        );
    }

    /**
     * @删除
     * @created 在 2021/11/30 17:26 创建
     * @param Request $request
     * @author: Sun Wu
     */
    public function del(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',//库存物料id
        ]);

        //参数错误响应
        if($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $data['main_id'] = $this->getMainUserId();
        $this->log('删除库存信息', $data);
        return response()->json(
            StorageManageService::del($data)
        );
    }

    public function detail(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required',//库存物料id
        ]);

        //参数错误响应
        if($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $this->log('查看库存详情', $data);
        return $this->success(StorageManageService::detail($data));
    }

    public function usedSerialList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'type_id' => 'required',//商品id
        ]);

        //参数错误响应
        if($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        return $this->success(StorageManageService::usedSerialList($data));
    }
    /**
     * 套件返仓
     */
    public function returnPackageStore(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'storage_manage_id' => 'required|integer',
            'product_id'     => 'required|integer',
            'product_num'     => 'required',
        ], [
            'storage_manage_id.required' => '参数`库存主键id`缺失',
            'storage_manage_id.integer' => '参数`库存主键id`仅能为数字',
            'product_id.required' => '参数`套件主键id`缺失',
            'product_id.integer' => '参数`套件主键id`仅能为数字',
            'product_num.required' => '参数`套件数量`缺失',
            /* 'product_num.integer' => '参数`套件数量`仅能为数字', */
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['user_id'] = $this->getUserId();
        $data['main_id'] = $this->getMainUserId();
        $data['time'] = time();

        $this->operateLog('套件返仓', $data, $data['time']);

        $result = storageManageService::handleReturnPackageStore($data);
        CommonService::operateResult($data['user_id'], $data['time'], $result);

        return response()->json($result);
    }

    /**
     * 库存查看序列号
     * Author: Sw
     * Created at 2023/2/28 9:37
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function serialList(Request $request)
    {
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'id' => 'required|integer',
            'type_id' =>'required|integer',
        ], [
            'id.required' => '参数`库存主键id`缺失',
            'id.integer' => '参数`库存主键id`仅能为数字',
            'type_id.required' => '参数`商品或套餐id`缺失',
            'type_id.integer' => '参数`商品或套餐id`仅能为数字',
        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return $this->fail('', $info);
        }

        $data['main_id'] = $this->getMainUserId();

        return $this->success(storageManageService::serialList($data));
    }

    public function materielStorageList(Request $request): \Illuminate\Http\JsonResponse
    {
        if(!empty($id = $request->input('id'))) {
            return $this->success(
                StorageManageService::materielStorageList($id)
            );
        }

        return $this->success();
    }
}
